<template>
	<el-card class="layout-query">
		<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="search()">
			<el-form-item label="问卷名称" prop="questionnaireName">
				<el-input v-model="state.queryForm.questionnaireName" placeholder="请输入" clearable></el-input>
			</el-form-item>
			<el-form-item label="问题名称" prop="questionContent">
				<el-input v-model="state.queryForm.questionName" placeholder="请输入" clearable> </el-input>
			</el-form-item>
			<el-form-item label="问题类型" prop="questionnaireType">
				<el-select v-model="state.queryForm.questionnaireType" placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="(item, index) in questionnaireType" :key="index" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="回复类型" prop="replyStatus">
				<el-select v-model="state.queryForm.replyStatus" placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="(item, index) in replyStatus" :key="index" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button icon="Search" type="primary" @click="search()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="reset()">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>
	<el-card>
		<el-form :inline="true" style="text-align: right" class="anniu">
			<el-form-item>
				<el-button type="primary" @click="exportHandle">导出汇总数据</el-button>
			</el-form-item>
		</el-form>
		<el-table v-loading="state.dataListLoading" :data="dataList">
			<el-table-column type="index" label="序号" width="55" align="center" />
			<el-table-column prop="questionnaireName" label="问卷名称" header-align="center" align="center" />
			<el-table-column prop="questionContent" label="问题描述" header-align="center" align="center" />
			<el-table-column prop="replyContent" label="具体回复" header-align="center" align="center" />
			<el-table-column prop="questionnaireType" label="问题类型" header-align="center" align="center">
				<template #default="scope">
					<el-tag v-if="scope.row.questionnaireType === '1'" type="success">问答题</el-tag>
					<el-tag v-else type="danger">是非题</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="replyName" label="回复人" header-align="center" align="center" />
			<el-table-column prop="replyOrg" label="回复人所在单位" header-align="center" align="center" />
			<el-table-column prop="replyTime" label="回复时间" header-align="center" align="center" />
			<el-table-column prop="replyStatus" label="回复状态" header-align="center" align="center">
				<template #default="scope">
					<span>{{ scope.row.replyStatus === '0' ? '未回复' : '已回复' }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" header-align="center" align="center" width="100">
				<template #default="scope">
					<el-icon
						v-if="scope.row.replyStatus === '1'"
						:size="16"
						title="查看"
						color="#1491FF"
						style="cursor: pointer; margin: 0 6px"
						@click="handleQuestionEdit(scope.row, true)"
					>
						<View />
					</el-icon>
					<el-icon
						v-else
						:size="16"
						title="回复"
						color="#1491FF"
						style="cursor: pointer; margin: 0 6px"
						@click="handleQuestionEdit(scope.row, false)"
					>
						<ChatLineRound />
					</el-icon>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.pageNum"
			:page-size="state.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		></el-pagination>
		<cmDialog v-model="showAddReply" modal-title="回复" model-width="600px">
			<el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
				<el-form-item label="问卷名称" prop="questionnaireName">{{ detailInfo.questionnaireName }}</el-form-item>
				<el-form-item label="问题描述" prop="questionContent">{{ detailInfo.questionContent }}</el-form-item>
				<el-form-item label="问题类型" prop="questionnaireType">
					{{ detailInfo.questionnaireType === '1' ? '问答题' : '是非题' }}
				</el-form-item>
				<el-form-item label="具体回复" prop="replyContent">
					<el-input
						v-model="formData.replyContent"
						placeholder="请输入"
						type="textarea"
						:rows="3"
						maxlength="500"
						show-word-limit
						:disabled="isView"
					></el-input>
				</el-form-item>
				<el-form-item label="回复人" prop="replyName">
					<el-input v-model="formData.replyName" placeholder="请输入" :disabled="isView"></el-input>
				</el-form-item>
				<el-form-item label="回复人所在单位" prop="replyOrg">
					<el-input v-model="formData.replyOrg" placeholder="请输入" :disabled="isView"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-foot">
					<el-button @click="showAddReply = false">关闭</el-button>
					<el-button v-if="!isView" type="primary" @click="submitForm(formRef)">提交</el-button>
				</div>
			</template>
		</cmDialog>
	</el-card>
</template>

<script setup lang="ts">
import { replyWenjuan, replyWenjuanList } from '@/api/other'
import cmDialog from '@/components/cm-dialog/index.vue'
import { useUserStore } from '@/store/modules/user'
import axios from 'axios'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'

const userStore = useUserStore()
const state = reactive({
	queryForm: {
		questionnaireName: '',
		questionnaireType: '',
		replyStatus: '',
		questionName: ''
	},
	pageNum: 1,
	pageSize: 10,
	total: 1,
	dataListLoading: false,
	keyType: '',
	keyword: null,
	yearrange: []
})
const dataList = ref([])
const questionnaireType = [
	{
		name: '问答题',
		code: '1'
	},
	{
		name: '是非题',
		code: '2'
	}
]
const replyStatus = [
	{
		name: '未回复',
		code: '0'
	},
	{
		name: '已回复',
		code: '1'
	}
]
const showAddReply = ref(false)
const formData = ref({
	detailId: '',
	replyContent: '',
	replyName: '',
	replyOrg: ''
})
const formRef = ref<FormInstance>()
const formRules = reactive<FormRules>({
	replyContent: [{ required: true, message: '请输入具体回复', trigger: 'blur' }],
	replyName: [{ required: true, message: '请输入回复人', trigger: 'blur' }],
	replyOrg: [{ required: true, message: '请输入回复人所在单位', trigger: 'blur' }]
})
const detailInfo = ref({
	questionnaireName: '',
	questionContent: '',
	questionnaireType: ''
})
const isView = ref<boolean>(false)

watch(
	() => showAddReply.value,
	val => {
		if (!val) {
			formData.value = {
				detailId: '',
				replyContent: '',
				replyName: '',
				replyOrg: ''
			}
		}
	}
)

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			replyWenjuan(formData.value).then(res => {
				ElMessage.success('操作成功！')
				showAddReply.value = false
				getDataList()
			})
		} else {
			if (!fields) {
				return
			}
		}
	})
}

const handleQuestionEdit = (row: any, view: boolean) => {
	isView.value = view
	detailInfo.value = {
		questionnaireName: row.questionnaireName,
		questionContent: row.questionContent,
		questionnaireType: row.questionnaireType
	}
	formData.value.detailId = row.detailId
	formData.value.replyContent = row.replyContent
	formData.value.replyName = row.replyName
	formData.value.replyOrg = row.replyOrg
	showAddReply.value = true
}

const search = () => {
	state.pageNum = 1
	getDataList()
}

const reset = () => {
	state.queryForm.questionnaireName = ''
	state.queryForm.questionnaireType = ''
	state.queryForm.replyStatus = ''
	state.queryForm.questionName = ''
	state.pageNum = 1
	getDataList()
}

const getDataList = () => {
	state.dataListLoading = true
	replyWenjuanList({
		pageNum: state.pageNum,
		pageSize: state.pageSize,
		...state.queryForm
	}).then(res => {
		state.dataListLoading = false
		dataList.value = res.data.list || []
		state.total = res.data.total || 0
	})
}

const exportHandle = () => {
	try {
		// const selectedRows = multipleTableRef.value.getSelectionRows()
		// if (selectedRows.length == 0) {
		// 	throw new Error('请选择一个项目')
		// }
		// const ids = selectedRows.map(item => {
		// 	return item.id
		// })
		axios({
			method: 'get',
			url: window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/questionnaire/reply/export',
			headers: {
				'Content-Type': 'application/json;charset=UTF-8',
				Authorization: userStore.token
			},
			responseType: 'blob'
		})
			.then(response => {
				ElMessage.success('操作成功，文件已开始下载')
				const blob = new Blob([response.data], {
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				})
				const url = window.URL.createObjectURL(blob)
				const a = document.createElement('a')
				a.href = url
				a.download = '问卷回复汇总数据.xlsx'
				a.click()
				window.URL.revokeObjectURL(url)
			})
			.catch(error => {
				console.error('导出失败:', error)
			})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const handleCurrentChange = (val: number) => {
	state.pageNum = val
	getDataList()
}
const handleSizeChange = (val: number) => {
	state.pageSize = val
	state.pageNum = 1
	getDataList()
}

onMounted(() => {
	getDataList()
})
</script>
<style scoped>
.anniu .el-form-item {
	margin-right: 10px !important;
}

.dialog-foot {
	display: flex;
	justify-content: center;
	margin-bottom: 10px;
	padding-bottom: 20px;
}
</style>
